<?php
/**
 * Created by b17
 * 2/15/12 5:18 PM
 */

namespace Managers;

class DeliveryEmail extends BaseManager implements CrudManager
{
    const TABLE = '\Catalog\DeliveryEmail';
    protected $__table = self::TABLE;

    /**
     * Создает новую запись.
     * @param array $values
     */
    public function create(array $values)
    {
        $this->throwIfRecordExists($values['email']);
        $entity = new \Catalog\DeliveryEmail();
        $entity->setIsDel(false);
        $this->setEntityValues($entity, $values);
        $this->_em->persist($entity);
        $this->flush();
        return $entity;
    }

    protected function setEntityValues(\Catalog\DeliveryEmail $entity, array $values)
    {
        $entity->setEmail($values['email']);
    }

    /**
     * Обновляет запись.
     * @param array $values
     */
    public function update(array $values)
    {
        $this->throwIfRecordExists($values['email']);
        $entity = $this->find($values['id']);
        if ($entity) {
            $this->setEntityValues($entity, $values);
            $this->_em->persist($entity);
            $this->flush();
        }
        return $entity;
    }

    /**
     * Возвращает елемент по ID, false - если елемент не найден.
     *
     * @param array|bool $id
     */
    public function getById($id)
    {
        $qb = $this->createQueryBuilder()
            ->andWhere('de.id = :id')->setParameter('id', $id);
        $res = $qb->getQuery()->getArrayResult();
        return count($res) ? $res[0] : false;
    }

    protected function createQueryBuilder()
    {
        $qb = $this->_em->createQueryBuilder()
            ->select('de')
            ->from($this->__table, 'de')
            ->andWhere('de.isDel = 0');
        return $qb;
    }

    public function getList()
    {
        $qb = $this->createQueryBuilder()
            ->orderBy('de.id', 'DESC');
        $res = $qb->getQuery()->getArrayResult();
        return $res;
    }

    private function throwIfRecordExists($email)
    {
        if ($this->recordExists($email)) {
            throw new \LogicException('Record with same email already exists.');
        }
    }

    public function recordExists($email)
    {
        $entity = $this->_em->getRepository($this->__table)->findOneBy(array('email' => $email, 'isDel' => 0));
        return (boolean) $entity;
    }

    public function saveImports($emails)
    {
        if (!is_array($emails) || !count($emails)) {
            throw new \LogicException('No email addresses to import');
        }

        foreach ($emails as $email) {
            if (!$this->recordExists($email)) {
                $entity = new \Catalog\DeliveryEmail();
                $this->setEntityValues($entity, array('email' => $email));
                $entity->setIsDel(false);
                $this->_em->persist($entity);
            }
        }
        $this->flush();
    }
}
